package com.example.wotu;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragBookDR.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragBookDR#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragBookDR extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private SQLiteDatabase sql;
    private int userid;
    private View view;
    private TextView LU;
    private ListView DRlist;
    private ArrayList<String> LINT,str_BT = new ArrayList<>(),str_NR = new ArrayList<>();
    private ArrayAdapter adp;
    private String path, wpath,WNAME;
    private int ce = 0, shuc = 0,CZ = 0;
    private BufferedReader br = null;
    private String BM = "UTF-8";
    private Handler handler;

    public FragBookDR() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragBookDR.
     */
    // TODO: Rename and change types and number of parameters
    public static FragBookDR newInstance(String param1, String param2) {
        FragBookDR fragment = new FragBookDR();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.frag_book_dr, container, false);
        return view;
    }

    //暂时不做
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userid = mListener.usei();
        DRlist = (ListView) view.findViewById(R.id.DRlist);
        LU = (TextView) view.findViewById(R.id.LU);
        getSDOR();
        ONSET();
    }

    //1.保存历史记录，判断SDcard是否存在并且可读写
    private void getSDOR() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                //1-1：获取根目录 (/storage/emulated/0)：于29弃用
                path = Environment.getExternalStorageDirectory().getCanonicalPath();
                LU.setText(path);
                CLPath(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else Toast.makeText(getActivity(), "不可用根目录", Toast.LENGTH_SHORT).show();
    }
    //2：处理路径 (/storage/emulated/0/Android)，输出固定格式
    private void CLPath(String LJin) {
        File[] FB = new File(LJin).listFiles();
        LINT = new ArrayList<>();
        if (FB == null) {
            LINT.add("...返回上一层");
        } else {
            if (ce > 0) LINT.add("...返回上一层");
            //分割“/”提取末尾路径
            for (int i = 0; i < FB.length; i++) {
                String[] fbi = String.valueOf(FB[i]).split("/");
                if (TestHZ(fbi[fbi.length - 1]) > 0) LINT.add(fbi[fbi.length - 1]);
            }
        }
        MList(LINT);
    }
    public int TestHZ(String ls) {
        if (ls.contains(".")) {
            String[] lsa = ls.split("\\.");
            if (lsa[lsa.length - 1].equals("txt")) return 2;
            else return 0;
        } else return 1;
    }
    //list处理
    private void MList(ArrayList<String> L) {
        adp = new ArrayAdapter(getActivity(), R.layout.support_simple_spinner_dropdown_item, L);
        DRlist.setAdapter(adp);
    }
    //点击
    private void ONSET() {
        DRlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //使用一个path，通过ce层次来进行确定层数处理
                if (ce > 0) {
                    if (i == 0) {
                        ce--;
                        String[] ga = path.split("/");
                        String gb = "/" + ga[1] + "/" + ga[2] + "/" + ga[3];
                        for (int v = 4, m = ce; v < ga.length; v++) {
                            if (m == 0) break;
                            else {
                                gb += "/" + ga[v];
                                m--;
                            }
                        }
                        path = gb;
                        LU.setText(path);
                        CLPath(path);
                    } else {
                        CLL(i);
                    }
                } else {
                    CLL(i);
                }
            }
        });
    }
    private void CLL(int i) {
        shuc = i;
        if (TestHZ(LINT.get(i)) == 2) {
            if(CZ == 1){
                Toast.makeText(getActivity(),"有文本已经在导入队列了！请等待！",Toast.LENGTH_SHORT).show();
            }else{
                new AlertDialog.Builder(getActivity())
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("红墨提示：")
                        .setMessage("是否将此文本导入？\n需要的时间可能稍长\n请等待...")
                        .setNeutralButton("确认", new DialogInterface.OnClickListener() {     //左边
                            @Override
                            public void onClick(DialogInterface dialogInterface, int s) {
                                String w = path + "/" + LINT.get(shuc);
                                DaoRu(w, LINT.get(shuc));
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create().show();
            }
        } else {
            ce++;
            path += "/" + LINT.get(i);
            LU.setText(path);
            CLPath(path);
        }
    }
    //当其不知文本编码时，记住：字符转字节，字节转字符
    public boolean ASC_GB(String w) {
        String[] s = w.split("");
        if(s.length>3){
            if(s[0].equals("�") || s[1].equals("�") || s[2].equals("�") || s[3].equals("�")) return false;
            else return true;
        }
        else if(s.length>0) return true;
        else{
            if(s[0].equals("�")) return false;
            else return true;
        }
    }
    //开启线程
    private void DaoRu(String w, String wname) {
        wpath = w;  //路径
        WNAME = wname;  //名称
        CZ = 1; //是否占用线程（后期改多条）
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                String strLing = "",bt = "";
                int ibm = 0,jls = 0;
                try {
                    //问题：导入他跳过乱码
                    //乱码：其一本身就是乱码；其二就需要转码如下；4
                    while (true){
                        //一行一行的读取有问题！会打乱原本文本的排序！
                        br = new BufferedReader(new InputStreamReader(new FileInputStream(wpath), BM));
                        while ((strLing = br.readLine()) != null) {
                            //判断调整符合文本编码格式
                            if(ASC_GB(strLing) == false) BM = "GB18030";
                            else ibm = 1;
                            break;
                        }
                        if(ibm == 1) break;
                    }
                    //存储数据
                    strLing = "";
                    ibm = 0;
                    br = new BufferedReader(new InputStreamReader(new FileInputStream(wpath), BM));
                    while ((strLing = br.readLine()) != null){
                        //判断第一次是否已达标题章
                        if(TFone(strLing)){
                            if(ibm == 1){
                                str_NR.add(bt);
                                bt = "";
                            }
                            str_BT.add(strLing.trim());
                            ibm = 1;
                            jls++;
                        }else if(ibm == 1){
                            bt += "\n"+strLing;
                        }
                    }
                    str_NR.add(bt);
                    handler.sendMessage(handler.obtainMessage(1));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new  Thread(runnable).start();
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1){
                    SQLDR_TXT();
                    Toast.makeText(getActivity(),WNAME+"已经导入成功！",Toast.LENGTH_SHORT).show();
                    WNAME = "";
                    CZ = 0;
                }
            }
        };
    }
    private void SQLDR_TXT(){
        sql = new MySQLOpen(getActivity()).getReadableDatabase();
        try{
            sql.beginTransaction();
            ContentValues val = new ContentValues();
            val.put("useid",userid);
            val.put("fwl",0);
            val.put("novelpath",0);
            val.put("novelname",WNAME);
            long L = sql.insert("novel",null,val);
            if(L > 0){
                int novid = 0;
                Cursor cs = sql.rawQuery("select novelid from novel order by novelid desc limit 0,1",null);
                while (cs.moveToNext()) novid = cs.getInt(0);
                for(int i = 0; i < str_BT.size(); i++){
                    ContentValues cvs = new ContentValues();
                    cvs.put("novelid",novid);
                    cvs.put("chapxl",(i+1));
                    cvs.put("chapname",str_BT.get(i));
                    cvs.put("content",str_NR.get(i));
                    sql.insert("chapter",null,cvs);
                }
                sql.setTransactionSuccessful();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sql.endTransaction();
            sql.close();    //这里关闭有问题！
        }
    }
    //处理章号（行）（第001章 你好吗？）
    public Boolean TFone(String fs) {

        String[] xTs = fs.trim().split("");
        for(int i=0,isn = 0;i<xTs.length;i++){
            if(xTs[i].length()>0){
                if(isn == 0){
                    if(xTs[i].equals("第") || BMJ(xTs[i])) isn = 1;
                    else return false;
                }else if(isn == 1){
                    if(BMJ(xTs[i]) == false){
                        if(xTs[i].equals("章")) return true;
                        else return false;
                    }
                }
            }
        }
        return false;
    }
    private boolean BMJ(String bmj){
        if (bmj.equals("0") || bmj.equals("1") || bmj.equals("2") || bmj.equals("3")
                || bmj.equals("4") || bmj.equals("5") || bmj.equals("6") || bmj.equals("7")
                || bmj.equals("8") || bmj.equals("9") || bmj.equals("壹") || bmj.equals("贰")
                || bmj.equals("叁") || bmj.equals("肆") || bmj.equals("陆") || bmj.equals("柒")
                || bmj.equals("捌") || bmj.equals("玖") || bmj.equals("零") || bmj.equals("拾")
                || bmj.equals("佰") || bmj.equals("仟") || bmj.equals("萬") || bmj.equals("亿")
                || bmj.equals("一") || bmj.equals("二") || bmj.equals("三") || bmj.equals("四")
                || bmj.equals("五") || bmj.equals("六") || bmj.equals("七") || bmj.equals("八")
                || bmj.equals("九") || bmj.equals("十") || bmj.equals("百") || bmj.equals("千")
                || bmj.equals("万")) {
            return true;
        }else return false;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        int usei();
    }
}
